package tjs.styudy.mini.springboot.devtools.config;

import org.springframework.boot.context.event.ApplicationPreparedEvent;
import org.springframework.boot.context.event.ApplicationStartingEvent;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class RestartApplicationListener implements ApplicationListener<ApplicationEvent> {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ApplicationStartingEvent) {
            onApplicationStartingEvent((ApplicationStartingEvent) event);
        }
        if (event instanceof ApplicationPreparedEvent) {
            onApplicationPreparedEvent((ApplicationPreparedEvent) event);
        }
    }

    public void onApplicationStartingEvent(ApplicationStartingEvent event) {
        // 初始化Restarter类，如果是首次调用就尝试重启main方法
        Restarter.initialize(event.getArgs());
    }

    public void onApplicationPreparedEvent(ApplicationPreparedEvent event) {
        // 重启main方法
        Restarter.getInstance().prepare(event.getApplicationContext());
    }
}